const Router = require("@koa/router");
const router = new Router();
const {
  LocalTravel,
  AddressQueryTravels,
  ChooseAddress,
} = require("@/config/valiData");
const { Auth } = require("@/token/auth");
const moment = require("moment");
moment.locale("zh-cn");
const fs = require("fs");
const path = require("path");
const {
  modelHometab,
  modelArticle,
  modelLocalWay,
  modelCountry,
  modelCity,
} = require("@/models/collection");
const { looKup } = require("@/config/lookup");
const { lookup } = require("dns");

//导入当地玩法到数据库
router.get("/loacl-database", async (ctx) => {
  const filePath = path.join(__dirname, "../../local.json");
  try {
    const citydata = fs.readFileSync(filePath);
    const res = JSON.parse(citydata);
    await modelLocalWay.insertMany(res);
    ctx.send("SUCCESS", 200, "数据导入成功");
  } catch (error) {
    console.error("读取文件错误:", error);
    ctx.send("ERROR", 500, "数据导入失败");
  }
});

//获取当地玩法
router.get("/local-gameplay", async (ctx) => {
  const res = await modelLocalWay.find();
  ctx.send("SUCCESS", 200, res);
});

//根据定位获取当地游记
router.get("/local-travel", async (ctx) => {
  const { page, address } = ctx.query;
  LocalTravel(page, address);
  const query = { $regex: address, $options: "i" };
  const res = await modelArticle.aggregate([
    {
      $match: {
        $or: [{ city: query }, { address: query }, { province: query }],
      },
    },
    { $skip: (page - 1) * 6 },
    { $limit: 6 },
    looKup().model_user,
    looKup().model_like,
    looKup().projectcard,
  ]);
  ctx.send("SUCCESS", 200, res);
});

//图片合集：查询选中的城市所有图片
router.get("/addressImage", async (ctx) => {
  const { page, address } = ctx.query;
  LocalTravel(page, address);

  const query = { $regex: address, $options: "i" };
  const res = await modelArticle
    .find({
      $or: [{ city: query }, { address: query }, { province: query }],
    })
    .skip((page - 1) * 10)
    .limit(10)
    .select("image")
    .lean();
  const imageData = res.flatMap((item) => item.image);
  console.log(imageData);

  ctx.send("SUCCESS", 200, imageData);
});

//当地玩法：按地址和游记分类查询游记
router.get("/addressQueryTravels", async (ctx) => {
  const { address, keywords, page } = ctx.query;
  AddressQueryTravels(address, keywords, page);
  const query = { $regex: keywords, $options: "i" };
  const res = await modelArticle.aggregate([
    {
      $match: {
        $and: [
          { city: address },
          {
            $or: [{ title: query }, { address: query }, { tag: query }],
          },
        ],
      },
    },
    { $skip: (page - 1) * 6 },
    { $limit: 6 },
    looKup().model_user,
    looKup().model_like,
    looKup().projectcard,
  ]);
  ctx.send("SUCCESS", 200, res);
});

//导入选择城市节目的国家和城市
router.get("/country-database", async (ctx) => {
  const filePath = path.join(__dirname, "../../city.json");
  try {
    const data = fs.readFileSync(filePath);
    const res = JSON.parse(data);
    await modelCity.insertMany(res);
    ctx.send("SUCCESS", 200, "数据导入成功");
  } catch (error) {
    console.error("读取文件错误:", error);
    ctx.send("ERROR", 500, "数据导入失败");
  }
});

//用户根据分类选择地址
router.get("/choose-address", async (ctx) => {
  const { type } = ctx.query;
  ChooseAddress(type);

  if (type === "AAA") {
    // 1. 热门城市查询 - 这部分是正确的
    const startOfMonth = moment().clone().startOf("month").unix();
    const endOfMonth = moment().clone().endOf("month").unix();
    const currentMonth = await modelArticle.aggregate([
      { $match: { time_stamp: { $gte: startOfMonth, $lte: endOfMonth } } },
      {
        $group: {
          _id: "$city",
          count: { $sum: 1 },
          image: { $first: "$cover_image.url" },
        },
      },
      { $sort: { count: -1 } },
      { $limit: 6 },
    ]);

    // 2. 自由行必去城市查询 - 需要修正 modelArticle.aggregate
    const freedom = await modelArticle.aggregate([
      { $unwind: "$tag" },
      { $match: { tag: "自由行" } },
      {
        $group: {
          _id: "$city",
          count: { $sum: 1 },
          image: { $first: "$cover_image.url" },
        },
      },
      { $sort: { count: -1 } },
      { $limit: 3 },
    ]);

    // 3. 热度飙升城市查询
    const heatCity = await modelArticle.aggregate([
      { $unwind: "$tag" },
      {
        $match: {
          like: { $exists: true }, // 或其他适当的条件
        },
      },
      {
        $group: {
          _id: "$city",
          count: { $sum: 1 },
          image: { $first: "$cover_image.url" },
        },
      },
      { $sort: { count: -1 } },
      { $limit: 3 },
    ]);

    const resobj = { currentMonth, freedom, heatCity };

    ctx.send("SUCCESS", 200, resobj);
  } else {
    const res = await modelCity.find({ type }, { type: false });
    ctx.send("SUCCESS", 200, res);
  }
});

//获取城市选中界面，进去页面获取左边的国家城市分类

router.get("/country-class", async (ctx) => {
  const res = await modelCountry.find();
  ctx.send("SUCCESS", 200, res);
});
module.exports = router.routes();
